import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class 事务处理 {

    @Test
    public void 转账(){
        Connection connection = null;

        try {
            connection = 连接.getConnection();
            connection.setAutoCommit(false);

            String sql1 = "update account set balance = balance - 100 where name = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.setString(1,"王康");
            preparedStatement.executeUpdate();

            // 模拟网络异常
            System.out.println(10 / 0);

            String sql2 = "update account set balance = balance + 100 where name = ?";
            PreparedStatement preparedStatement1 = connection.prepareStatement(sql2);
            preparedStatement1.setString(1,"陈仪鑫");
            preparedStatement1.executeUpdate();

            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } finally {
            if (connection != null){
                try {
                    connection.setAutoCommit(true);
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
